import store from './store'
import router from './router/index'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui';
const writelist = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
    Nprogress.start()
    const token = store.getters.token
    if (token) {
        const userInfo = store.getters.userinfo
        if (!userInfo.username) {
            // 说明用户信息不存在，需要重新发送请求
            let obj = await store.dispatch('user/getInfoapi') // 异步代码
            let newroutes = await store.dispatch('permission/settouter', obj.roles.menus)
            router.addRoutes([...newroutes, { path: '*', redirect: '/404', hidden: true }])
            if (to.path == '/login') {
                Message({
                    message: '您已经登录，请不要重复登录',
                    type: 'warning'
                });
                next('/dashboard')
            } else {
                next(to.path)
            }
        } else {
            if (to.path == '/login') {
                Message({
                    message: '您已经登录，请不要重复登录',
                    type: 'warning'
                });
                next('/dashboard')
            } else {
                next()
            }
        }

    } else {
        if (writelist.indexOf(to.path) > -1) {
            //在writelist中就返回下标，不在返回-1
            next()
        } else {
            next({
                path: '/login',
                query: {
                    back: to.path
                }
            })
            Message({
                message: '对不起，请先登录',
                type: 'warning'
            });
        }
    }
    Nprogress.done()
})
router.afterEach((to, from) => {
    Nprogress.done()
})